package com.ng.form.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ng.common.security.SecurityUtils;
import com.ng.common.service.CacheServiceImpl;
import com.ng.common.utils.PageUtils;
import com.ng.common.validator.Assert;
import com.ng.form.dao.FormTemplateDao;
import com.ng.form.entity.FormTemplateEntity;
import com.ng.form.service.FormTemplateService;
import com.ng.form.validator.NgFormValidator;
import com.ng.form.validator.entity.FormValidator;
import com.ng.sys.entity.SysUserEntity;
 


@Service("formTemplateService")
public class FormTemplateServiceImpl extends CacheServiceImpl<FormTemplateDao, FormTemplateEntity> implements FormTemplateService {

	@Autowired
	private SecurityUtils securityUtils;
	
	private NgFormValidator ngFormValidator ;
	
    @Override
    public PageUtils queryPage(FormTemplateEntity entity , PageUtils page ) {
        
        IPage<FormTemplateEntity> ipage = baseMapper.page(page.getPage(FormTemplateEntity.class), entity);
        return new PageUtils(ipage);
    }
    
    @Override
    public boolean save(FormTemplateEntity entity) {
    	
    	SysUserEntity user = securityUtils.getCurrentUser();
    	
    	entity.setCreateTime(new Date());
    	entity.setCreateId(user.getUserId());
    	entity.setStatus(0);
    	entity.setVersion(1);
    	
    	// 找编码
    	String maxCode = baseMapper.getMaxCode();
    	String code = "F00001" ;
    	if(maxCode != null) {
    		code = "F" + StringUtils.leftPad(String.valueOf(Integer.valueOf(maxCode) + 1), 5 , "0");
    	} 
    	entity.setCode(code);
    	
    	return super.save(entity);
    }
    
    public static void main(String[] args) {
		
    	String code = "00001" ;
    	
    	System.out.println(StringUtils.leftPad(String.valueOf(Integer.valueOf(code) + 1), 5 , "0"));
    	
	}
    
    @Override
    public boolean updateById(FormTemplateEntity entity) {
    	SysUserEntity user = securityUtils.getCurrentUser();
    	entity.setUpdateTime(new Date());
    	entity.setUpdateId(user.getUserId());
    	
    	// 根据ID 查询出来当前数据
    	FormTemplateEntity templdate = getById(entity.getId());
    	//判断之前的状态
    	if(templdate.getStatus() == 1) {
    		// 当前已发布 这里新增一个版本号
    		templdate.setVersion(templdate.getVersion() + 1);
    		templdate.setStatus(0);
    		templdate.setTemplateData(entity.getTemplateData());
    		templdate.setUpdateId(user.getUserId());
    		templdate.setUpdateTime(new Date());
    		templdate.setId(null);
    		
    		boolean save = super.save(templdate);
    		entity.setId(templdate.getId());
    		return save ;
    	} else {
    		// 当前版本是暂存  继续暂存
    		// 当前已发布 这里新增一个版本号  
    		templdate.setTemplateData(entity.getTemplateData());
    		templdate.setUpdateId(user.getUserId());
    		templdate.setUpdateTime(new Date());
    		 
    		return super.updateById(entity);
    	} 
    
    }

	@Override
	public boolean publish(String id) {
		
		// 根据ID 查询出来当前数据
		FormTemplateEntity update = new FormTemplateEntity();
		update.setId(id);
		update.setStatus(1);
		
		return super.updateById(update);
	}

	@Override
	public FormTemplateEntity queryByCode(String code) {
		
		QueryWrapper<FormTemplateEntity> query = new QueryWrapper<>();
		query.eq("code", code);
		query.eq("status", 1);
		query.orderByDesc("version");
		query.last(" limit 1");
		
		return getOne(query, false);
	}

	@Override
	public boolean revoke(String id) {
		
		FormTemplateEntity templdate = getById(id);
		
		Assert.expression(templdate.getStatus() == 1, "已发布模板不能被撤销");
		 
		return removeById(id);
	}

	@Override
	public String validatorFormData(JSONObject data, String formId) {

		FormTemplateEntity template =  getById(formId);
		
		Assert.isNull(template, "模板不存在或已被删除");
		
		String templateData = template.getTemplateData();
		
		Assert.isBlank(templateData, "模板不存在或已被删除");
		
		JSONObject templateJson = JSON.parseObject(templateData);
		
		if(ngFormValidator == null) {
			ngFormValidator = new NgFormValidator();
		}
		
		FormValidator fv = ngFormValidator.validator(templateJson, data);
		
		if(fv == null || fv.getResult() || fv.getFailField() == null ) {
			return null;
		}
		
		StringBuilder sb = new StringBuilder();
		fv.getFailField().stream().forEach(t-> {
			String s = t.getMessage();
			sb.append(s + ";");
		});
		
		return sb.toString();
	}

}
